package _2022.hot100._104_二叉树的最大深度;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author： YHSimon
 * @date： 2022-04-25 21:47
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {

    //1ms  bfs
    public int maxDepth(TreeNode root) {
        int ans = 0;
        if (root == null) {
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }

    // dfs 0ms
    public int maxDepth2(TreeNode root){
        if(root==null){
            return 0;
        }

        return Math.max(dfs(root.left, 1), dfs(root.right,1));
    }

    public int dfs(TreeNode node,int depth) {
        if(node==null){
            return depth;
        }

        return Math.max(dfs(node.left, depth+1), dfs(node.right, depth+1));
    }

    //dfs 0ms
    public int maxDepth3(TreeNode root){
        if (root==null){
            return 0;
        }else{
            int leftHeight=maxDepth3(root.left);
            int rightHeight=maxDepth3(root.right);
            return Math.max(leftHeight, rightHeight)+1;
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        TreeNode root = new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
        System.out.println(s.maxDepth2(root));
    }
}
